package com.arcvideo.acsconnect.widget;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.media.MediaPlayer;
import android.support.annotation.NonNull;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.arcvideo.acsconnect.app.GlobalConstant;
import com.arcvideo.acsconnect.bean.MessageBean;
import com.arcvideo.rtcmessage.utils.LogUtil;
import com.arcvideo.tyingyitonginhouse.R;
import com.bumptech.glide.Glide;
import com.framework.core.utils.ToastUtil;
import com.framework.core.widget.CircleImageView;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * @author shenmengchao
 * @version 1.0.0
 * @date 2017/7/28
 * @description
 */

public class InviteDialog extends Dialog implements View.OnFocusChangeListener {

    private final static String TAG = InviteDialog.class.getSimpleName();

    @BindView(R.id.iv_avatar)
    CircleImageView mIvAvatar;
    @BindView(R.id.tv_des)
    TextView mTvDes;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.iv_invite)
    ImageView mIvInvite;
    @BindView(R.id.ll_avatar)
    LinearLayout mLlAvatar;
    @BindView(R.id.iv_answer)
    ImageView mIvAnswer;
    @BindView(R.id.iv_hang_up_invite)
    ImageView mIvHangUpInvite;
    @BindView(R.id.tv_confirm)
    TextView mTvConfirm;
    @BindView(R.id.tv_reject)
    TextView mTvReject;
    @BindView(R.id.ll_confirm)
    LinearLayout mLlConfirm;
    private Context mContext;
    private Activity mActivity;
    private MessageBean mMessageBean;

    private OnConfirmListener mOnConfirmListener;
    private Subscription mSubscription;
    private MediaPlayer mMediaPlayer;

    public InviteDialog(@NonNull Activity activity, MessageBean messageBean) {
        super(activity, R.style.Dialog);
        this.mContext = activity;
        this.mActivity = activity;
        this.mMessageBean = messageBean;
//        this.mDes = des;
        init();
        initView();
        initEvent();
    }

    public void setOnConfirmListener(OnConfirmListener listener) {
        this.mOnConfirmListener = listener;
    }

    public String getUserId() {
        if (null != mMessageBean) {
            return mMessageBean.getId();
        }
        return "";
    }

    private void init() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_dialog_invite, null, false);
        ViewGroup.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        ButterKnife.bind(this, view);
        addContentView(view, layoutParams);

        Window window = this.getWindow();
        WindowManager m = window.getWindowManager();
        Display d = m.getDefaultDisplay();
        WindowManager.LayoutParams p = window.getAttributes();
        p.width = (int) (d.getWidth() * 0.35);
        p.height = (int) (d.getHeight() * 0.7);
        window.setAttributes(p);
        mIvAnswer.requestFocus();
        mMediaPlayer = MediaPlayer.create(mContext, R.raw.dialing);

        /** 添加dismiss callback，当dialog消失的时候，停止计时器已经关闭MediaPlayer 拨号音**/
//        setOnDismissListener(new OnDismissListener() {
//            @Override
//            public void onDismiss(DialogInterface dialog) {
//                doOnDismiss();
//            }
//        });
    }

    private void initView() {
        Glide.with(mActivity).load(mMessageBean.getIconurl()).into(mIvAvatar);
        String des = mMessageBean.getNickname() + " 正在向您发送视频通话请求\n是否接受?";
        mTvDes.setText(des);
    }

    private void initEvent() {
        mIvAnswer.setOnFocusChangeListener(this);
        mIvHangUpInvite.setOnFocusChangeListener(this);
    }

    private void doOnDismiss(){
        LogUtil.d(TAG, "doOnDismiss()");
        if (null != mSubscription) {
            mSubscription.unsubscribe();
        }
        LogUtil.d(TAG, "doOnDismiss(),mMediaPlayer == null : " + (mMediaPlayer == null));
        LogUtil.d(TAG, "doOnDismiss(),mMediaPlayer.isPlaying() : " + (mMediaPlayer.isPlaying()));
        if (null != mMediaPlayer) {
//            ToastUtil.showToast("停止拨号音");
            LogUtil.d(TAG, "doOnDismiss(), 停止拨号音");
            try{
                mMediaPlayer.pause();
                mMediaPlayer.stop();
                mMediaPlayer.release();
            }catch (Exception e){
                LogUtil.d(TAG, "doOnDismiss(), 停止拨号音出现异常 " + e.getMessage());
            }

        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_ENTER:     //确定键enter
            case KeyEvent.KEYCODE_DPAD_CENTER:
                break;
            case KeyEvent.KEYCODE_BACK:
                dismiss();
                break;
            default:
                break;
        }

        return super.onKeyDown(keyCode, event);
    }

    @OnClick({R.id.iv_answer, R.id.iv_hang_up_invite})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_answer:
                if (null != mOnConfirmListener) {
                    mOnConfirmListener.onConfirm(mMessageBean.getId());
                }
                dismiss();
                break;
            case R.id.iv_hang_up_invite:
                if (null != mOnConfirmListener) {
                    mOnConfirmListener.onReject(mMessageBean.getId());
                }
                dismiss();
                break;
        }
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        switch (v.getId()) {
            case R.id.iv_answer:
                if (hasFocus) {
                    mIvAnswer.setImageResource(R.mipmap.ic_answer_checked);
                } else {
                    mIvAnswer.setImageResource(R.mipmap.ic_answer);
                }
                break;
            case R.id.iv_hang_up_invite:
                if (hasFocus) {
                    mIvHangUpInvite.setImageResource(R.mipmap.ic_hangup_invite_checked);
                } else {
                    mIvHangUpInvite.setImageResource(R.mipmap.ic_hangup_invite);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void show() {
        super.show();
        mSubscription = Observable.interval(1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Long>() {
                    @Override
                    public void call(Long aLong) {
                        if (aLong > GlobalConstant.DIALING_TIMEOUT) {
                            LogUtil.d(TAG, "show() subscribe() 长时间无应答，已自动关闭");
                            dismiss();
                            ToastUtil.showToast("长时间无应答，已自动关闭");
                        }
                    }
                });
        if (null != mMediaPlayer && !mMediaPlayer.isPlaying()) {
            mMediaPlayer.start();
            mMediaPlayer.setLooping(true);
        }
    }

    @Override
    public void dismiss() {
        super.dismiss();
        doOnDismiss();
    }

    public interface OnConfirmListener {

        void onConfirm(String id);

        void onReject(String id);
    }
}
